package gui.admin.ticketsinfor;


import database.TableDatabaseUsage;
import gui.admin.ManageFlights;
import gui.ATM;
import gui.admin.mtm.ATM1;
import gui.admin.mtm.TTM;
import info.Ticket;
import messages.flight.AddInfoResponeMessage;
import messages.flight.DeFLliInfoResponseMessage;
import messages.flight.UPFLliInfoResponseMessage;
import messages.ticket.*;
import server.MessageServer;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.io.IOException;
import java.sql.Date;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;


public class Fee_Tickets extends JFrame {
    private String ticketType;
    private JTable jTable;
    private Ticket Fticket = new Ticket();
    public Fee_Tickets(){
        setTitle("票务费用管理");
        setSize(700, 500);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        Fee();
        setResizable(false);
        setVisible(true);
    }
    private void Fee(){
        jTable= new JTable(TTM.getInstance());
        //头部欢迎文字
        JPanel jp = new JPanel();
        jp.setBounds(130, 30, 500, 60);
        JLabel jL = new JLabel("欢迎使用票务费用管理系统！");

        //创建文字对象

        jL.setFont(new Font("楷体", Font.BOLD, 33));
        jL.setForeground(Color.darkGray);
        jp.add(jL);
        this.add(jp);
        JButton btn1 = new JButton("查询");
        JButton btn2 = new JButton("增加票种");
        JButton btn3 = new JButton("删除票种");
        JButton btn4 = new JButton("修改费用");
        JPanel panel = new JPanel();


        //查询按钮
        btn1.setBounds(285, 100, 90, 35);


        this.getContentPane().add(btn1);
        btn2.setBounds(50,400,125,35);
        btn2.addActionListener(e -> {
            System.out.println("增加按钮被点击了");
            /*增加票种*/
            new AddFlightsTicketInfoForm(Fticket);
            TTM.getInstance().flightTicket=TableDatabaseUsage.getInstance().getTicketList();
            jTable.updateUI();

        });
        btn3.setBounds(280,400,125,35);
        btn3.addActionListener(e -> {
            System.out.println("删除按钮被点击了");
            int selectedRow=jTable.getSelectedRow();
            if(selectedRow!=-1){
                int response = JOptionPane.showConfirmDialog(null, "确认删除吗！", "删除确认", JOptionPane.YES_NO_OPTION);
                String flighted = (String) jTable.getValueAt(selectedRow,0);

                System.out.println("你删除航班为"+flighted);
                // 根据用户选择执行相应操作
                if (response == JOptionPane.YES_OPTION) {
                    // 用户选择了“是”，执行删除操作
                    System.out.println("用户确认删除");
                    sendDeleteFlightsTicketInfoMsg(flighted);
                    JOptionPane.showMessageDialog(null, "删除成功！", "操作成功", JOptionPane.INFORMATION_MESSAGE);
                    TTM.getInstance().flightTicket=TableDatabaseUsage.getInstance().getTicketList();
                    jTable.updateUI();
                    // 在这里添加删除逻辑
                } else if (response == JOptionPane.NO_OPTION) {
                    // 用户选择了“否”，取消删除操作
                    System.out.println("用户取消删除");
                    JOptionPane.showMessageDialog(null, "您已取消删除！", "操作失败", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    // 用户关闭了对话框或点击了其他按钮（如果有）
                    System.out.println("用户关闭了对话框或点击了其他按钮");
                }

            }else {
                JOptionPane.showMessageDialog(null, "请选择一行进行删除！");
            }

        });
        btn4.setBounds(510,400,125,35);
        btn4.addActionListener(e -> {
            System.out.println("修改费用按钮被点击了");
            int selectedRow=jTable.getSelectedRow();
            if(selectedRow!=-1){
                String flighted = (String) jTable.getValueAt(selectedRow,0);
                Date Fdated=(Date) jTable.getValueAt(selectedRow,1);
                String Fclassed=(String) jTable.getValueAt(selectedRow,2);
                Float Priced=(float) jTable.getValueAt(selectedRow,3);
                int Ticketed=(int) jTable.getValueAt(selectedRow,4);

                System.out.println("你选择航班为"+flighted);
                Fticket1.setFlight(flighted);
                Fticket1.setFdate(Fdated);
                Fticket1.setFclass(Fclassed);
                Fticket1.setPrice(Priced);
                Fticket1.setTicket(Ticketed);
                System.out.println("_____"+Ticketed);
                System.out.println("_____"+Fticket1.getTicket());
                new UpdateFlightsTicketInfoForm();
            }else {
                JOptionPane.showMessageDialog(null, "请选择一行进行修改！");
            }
        });
        this.getContentPane().add(btn2);
        this.getContentPane().add(btn3);
        this.getContentPane().add(btn4);
        //票种类型
        JLabel TicketTypeLabel = new JLabel("票种类型");
        TicketTypeLabel.setBounds(50, 100, 100, 35);
        String[] TypeOptions = {"全部舱型","头等舱", "商务舱", "经济舱"};
        JComboBox jComboBox = new JComboBox<>(TypeOptions);
        jComboBox.setBounds(130, 100, 150, 35);
        ticketType="全部舱型";
        jComboBox.addActionListener(e->{
            int i;
            i=jComboBox.getSelectedIndex();

            switch (i){
                case 1:
                    ticketType="头等舱";
                    break;
                case 2:
                    ticketType="商务舱";
                    break;
                case 3:
                    ticketType="经济舱";
                    break;
                default:
                    ticketType="全部舱型";
                    break;
            }
            System.out.println("您选择的票种是："+ticketType);

        });
        System.out.println("您选择的票种是："+ticketType);
        this.getContentPane().add(TicketTypeLabel);
        this.getContentPane().add(jComboBox);
        this.getContentPane().add(panel);
        btn1.addActionListener(e -> {
            System.out.println("查询按钮被点击了！");
            System.out.println(ticketType);
            if(ticketType!="全部舱型") {
                TTM.getInstance().flightTicket = TableDatabaseUsage.getInstance().getTicketList1(ticketType);
            }else {
                TTM.getInstance().flightTicket = TableDatabaseUsage.getInstance().getTicketList();
            }
            jTable.updateUI();
        });
        //表格


        JScrollPane scroll = new JScrollPane(jTable);

        scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scroll.setPreferredSize(new Dimension(620, 200));
        jTable.setBackground(Color.white);
        jTable.setRowHeight(40);

        jTable.setGridColor(Color.pink);
        jTable.setSelectionBackground(Color.orange);
        //使表格文字居中
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();

        centerRenderer.setHorizontalAlignment(JLabel.CENTER);


        for (int i = 0; i < jTable.getColumnCount(); i++) {
            jTable.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);

        }
        panel.setBorder(BorderFactory.createEmptyBorder(150, 0, 0, 0));
        panel.add(scroll);
    }
    /*发送删除消息*/
    private boolean sendDeleteFlightsTicketInfoMsg(String flighted) {
        DeFlightsTicketsReqMsg deFlightsTicketsReqMsg = new DeFlightsTicketsReqMsg();
        DeFlightsTicketsResMsg deFlightsTicketsResMsg;
        deFlightsTicketsReqMsg.setOldFliId(flighted);
        try {
            MessageServer.getInstance().getOos().writeObject(deFlightsTicketsReqMsg);
            System.out.println("客户端发送请求成功！"+deFlightsTicketsReqMsg);
            deFlightsTicketsResMsg = (DeFlightsTicketsResMsg) MessageServer.getInstance().
                    getOis().readObject();
            System.out.println("客户端收到服务端的响应成功！"+deFlightsTicketsResMsg);
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return true;
    }

        private Ticket Fticket1=new Ticket();
    class AddFlightsTicketInfoForm extends JFrame{
        JTextField FlightTextField;
        JTextField FdateTextField;
        JTextField FclassTextField;
        JTextField FpriceTextField;
        JTextField FticketsTextField;

        private Ticket newTicket=new Ticket();
        public AddFlightsTicketInfoForm(Ticket ticket){
            super("增加航班票种信息");
            setSize(500,500);
            setLayout(new GridLayout(6,2));
            FlightTextField = new JTextField(ticket.getFlight());
            FdateTextField = new JTextField(String.valueOf(ticket.getFdate()));
            FclassTextField = new JTextField(ticket.getFclass());
            FpriceTextField = new JTextField(String.valueOf(ticket.getPrice()));
            FticketsTextField = new JTextField(ticket.getTicket());
            JButton AddInfoButton = new JButton("确认增加");
            AddInfoButton.addActionListener(e->{
                newTicket.setFlight(FlightTextField.getText());
                newTicket.setFdate(Date.valueOf(FdateTextField.getText()));
                newTicket.setFclass(FclassTextField.getText());
                newTicket.setPrice(Float.valueOf(FpriceTextField.getText()));
                newTicket.setTicket(Integer.parseInt(FticketsTextField.getText()));
                if(sendAddFlightsTicketInfoMsg(newTicket)){
                JOptionPane.showMessageDialog(null, "操作成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                dispose();
                }else {
                    JOptionPane.showMessageDialog(null, "操作失败，请重试。", "错误", JOptionPane.ERROR_MESSAGE);
                }
            });
            JLabel l1 = new JLabel("航班号：");
            JLabel l2 = new JLabel("起飞时间：");
            JLabel l3 = new JLabel("机票类型：");
            JLabel l4 = new JLabel("价格：");
            JLabel l5 = new JLabel("余票：");

            //设置居中
            l1.setHorizontalAlignment(JLabel.CENTER);
            l2.setHorizontalAlignment(JLabel.CENTER);
            l3.setHorizontalAlignment(JLabel.CENTER);
            l4.setHorizontalAlignment(JLabel.CENTER);
            l5.setHorizontalAlignment(JLabel.CENTER);

            add(l1);
            add(FlightTextField);
            add(l2);
            add(FdateTextField);
            add(l3);
            add(FclassTextField);
            add(l4);
            add(FpriceTextField);
            add(l5);
            add(FticketsTextField);

            add(new JLabel(""));
            add(AddInfoButton);

            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            setVisible(true);
        }
        private boolean sendAddFlightsTicketInfoMsg(Ticket newTicket){
            ADFlightsTicketReqInfoMes adFlightsTicketReqInfoMes = new  ADFlightsTicketReqInfoMes(newTicket);
            ADFlightsTicketResInfoMes adFlightsTicketResInfoMes;
            adFlightsTicketReqInfoMes.setTicket(newTicket);
            try{
                MessageServer.getInstance().getOos().writeObject(adFlightsTicketReqInfoMes);
                System.out.println("客户端发送请求成功！"+adFlightsTicketReqInfoMes);
                adFlightsTicketResInfoMes = (ADFlightsTicketResInfoMes) MessageServer.getInstance().
                        getOis().readObject();
                System.out.println("客户端收到服务端的响应成功！"+adFlightsTicketResInfoMes);
                return true;
            }catch (IOException | ClassNotFoundException e){
                System.out.println("请求超时");
                throw new RuntimeException(e);
            }
        }
}
    class UpdateFlightsTicketInfoForm extends JFrame{
//        String flighted = (String) jTable.getValueAt(selectedRow,0);
//        Date Fdated=(Date) jTable.getValueAt(selectedRow,1);
//        String Fclassed=(String) jTable.getValueAt(selectedRow,2);
//        Float Priced=(float) jTable.getValueAt(selectedRow,3);
//        int Ticketed=(int) jTable.getValueAt(selectedRow,4);
        JTextField FlightTextField;
        JTextField FdateTextField;
        JTextField FclassTextField;
        JTextField FpriceTextField;
        JTextField FticketsTextField;
        private String oldFlightTicketId;
        private Ticket newTicket=new Ticket();
        public UpdateFlightsTicketInfoForm(){
            super("修改费用信息");
            setLayout(new GridLayout(6,2));
            setSize(500,500);
            FlightTextField = new JTextField(Fticket1.getFlight());
            FdateTextField = new JTextField(String.valueOf(Fticket1.getFdate()));
            FclassTextField = new JTextField(Fticket1.getFclass());
            FpriceTextField = new JTextField(String.valueOf(Fticket1.getPrice()));
            FticketsTextField = new JTextField(String.valueOf(Fticket1.getTicket()));
            System.out.println("+++++"+Fticket1.getTicket());
            System.out.println("+++++"+FticketsTextField.getText());
            FlightTextField.setEditable(false);
            FdateTextField.setEditable(false);
            FclassTextField.setEditable(false);
            FticketsTextField.setEditable(false);
            JButton UpdateInfoButton = new JButton("确认修改");
            UpdateInfoButton.addActionListener(e->{
                newTicket.setFlight(FlightTextField.getText());
                newTicket.setFdate(Date.valueOf(FdateTextField.getText()));
                newTicket.setFclass(FclassTextField.getText());
                newTicket.setPrice(Float.valueOf(FpriceTextField.getText()));
                newTicket.setTicket(Integer.parseInt(FticketsTextField.getText()));
                oldFlightTicketId= newTicket.getFlight();
                if(sendUpdateFlightsTicketInfoMsg(newTicket,oldFlightTicketId)){
                    JOptionPane.showMessageDialog(null, "操作成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                    dispose();
                }else {
                    JOptionPane.showMessageDialog(null, "操作失败，请重试。", "错误", JOptionPane.ERROR_MESSAGE);
                }
            });
            JLabel l1 = new JLabel("航班号：");
            JLabel l2 = new JLabel("起飞时间：");
            JLabel l3 = new JLabel("机票类型：");
            JLabel l4 = new JLabel("价格：");
            JLabel l5 = new JLabel("余票：");

            //设置居中
            l1.setHorizontalAlignment(JLabel.CENTER);
            l2.setHorizontalAlignment(JLabel.CENTER);
            l3.setHorizontalAlignment(JLabel.CENTER);
            l4.setHorizontalAlignment(JLabel.CENTER);
            l5.setHorizontalAlignment(JLabel.CENTER);

            add(l1);
            add(FlightTextField);
            add(l2);
            add(FdateTextField);
            add(l3);
            add(FclassTextField);
            add(l4);
            add(FpriceTextField);
            add(l5);
            add(FticketsTextField);

            add(new JLabel(""));
            add(UpdateInfoButton);

            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            setVisible(true);
        }
        private boolean sendUpdateFlightsTicketInfoMsg(Ticket ticket, String oldFlightTicketId) {
            UpFliTicketsReqMsg upFliTicketsReqMsg = new UpFliTicketsReqMsg(ticket);
            UpFliTicketsResMsg upFliTicketsResMsg;
            upFliTicketsReqMsg.setTicket(ticket);
            upFliTicketsReqMsg.setOldFlightTicketId(oldFlightTicketId);
            try {
                MessageServer.getInstance().getOos().writeObject(upFliTicketsReqMsg);
                System.out.println("客户端发送请求成功！"+upFliTicketsReqMsg);
                upFliTicketsResMsg = (UpFliTicketsResMsg) MessageServer.getInstance().
                        getOis().readObject();
                System.out.println("客户端收到服务端的响应成功！"+upFliTicketsResMsg);
            } catch (IOException | ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
            updateFliTicInfo(upFliTicketsResMsg.getNewTicket());
            return true;
        }
        private void updateFliTicInfo(Ticket newTicket){
            Fticket1.setFlight(newTicket.getFlight());
            Fticket1.setFdate(newTicket.getFdate());
            Fticket1.setFclass(newTicket.getFclass());
            Fticket1.setPrice(newTicket.getPrice());
            Fticket1.setTicket(newTicket.getTicket());
        }

    }



}
